﻿using ExcelSystem.Model;
using ExcelSystem.ToolClass;
using ExcelSystem.ToolHelper;
using ExcelSystem.ViewModelsClass;
using ImTools;
using Newtonsoft.Json;
using NPOI.Util;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ExcelSystem.ViewModels
{
    public class BOMAddYMViewModel : BindableBase, IDialogAware
    {
        public string Title =>"";

        ExcelContext db;

        private BOMYM bomYM;
        public BOMYM BomYM
        {
            get { return bomYM; }
            set { SetProperty(ref bomYM, value); }
        }

        private List<NSMaterialsViewModel> nsMaterials;
        public List<NSMaterialsViewModel> NSMaterials
        {
            get { return nsMaterials; }
            set { SetProperty(ref nsMaterials, value); }
        }
        private MaterialViewModel model;

        private BOM Bom;


        public event Action<IDialogResult> RequestClose;

        private DelegateCommand<string> changeParCommand;
        /// <summary>
        /// 修改参数
        /// </summary>
        public DelegateCommand<string> ChangeParCommand
        {
            get { return changeParCommand; }
            set { SetProperty(ref changeParCommand, value); }
        }

        private DelegateCommand<string> addCommand;
        /// <summary>
        /// 新增
        /// </summary>
        public DelegateCommand<string> AddCommand
        {
            get { return addCommand; }
            set { SetProperty(ref addCommand, value); }
        }


        

        private DelegateCommand<string> saveCommand;
        /// <summary>
        ///  保存
        /// </summary>
        public DelegateCommand<string> SaveCommand
        {
            get { return saveCommand; }
            set { SetProperty(ref saveCommand, value); }
        }

        private DelegateCommand<string> deleteCommand;
        /// <summary>
        ///  保存
        /// </summary>
        public DelegateCommand<string> DeleteCommand
        {
            get { return deleteCommand; }
            set { SetProperty(ref deleteCommand, value); }
        }

        private DelegateCommand<string> pictrueSelectCommand;
        /// <summary>
        ///  图片保存
        /// </summary>
        public DelegateCommand<string> PictrueSelectCommand
        {
            get { return pictrueSelectCommand; }
            set { SetProperty(ref pictrueSelectCommand, value); }
        }

        








        private readonly IRegionManager regionManage;
        private readonly IDialogService dialogService;
        BOMAddYMViewModel(IRegionManager regionManage, IDialogService dialogService)
        {
            //数据库文档
            db = ExcelContentFactory.GetInstance() ;
            //依赖注入
            this.regionManage = regionManage;
            this.dialogService = dialogService;
            ChangeParCommand = new DelegateCommand<string>(ChangePar);
            SaveCommand = new DelegateCommand<string>(Save);
            DeleteCommand = new DelegateCommand<string>(Delete);
            PictrueSelectCommand = new DelegateCommand<string>(PictrueSelect);
            AddCommand = new DelegateCommand<string>(Add);


            Init();
        }

        private void Add(string obj)
        {
            if (BomYM.BOMChildInfo == null)
                BomYM.BOMChildInfo = new ObservableCollection<BOMChildInfo>();
            BomYM.BOMChildInfo.Add(new BOMChildInfo());

        }

        private void PictrueSelect(string obj)
        {
            var fileNames = OpenDialogs();
            if (fileNames == null)
                return;
            switch(obj)
            {
                case "Pictrue1":
                    BomYM.Pictrue1 = new KeyValue<string>() { Key = fileNames.SafeFileName, Value = fileNames.FileName };
                    break;
                case "Pictrue2":
                    BomYM.Pictrue2 = new KeyValue<string>() { Key = fileNames.SafeFileName, Value = fileNames.FileName };
                    break;
                case "Pictrue3":
                    BomYM.Pictrue3 = new KeyValue<string>() { Key = fileNames.SafeFileName, Value = fileNames.FileName };
                    break;

            }    
        }

        private void Save(string obj)
        {
            var base_info = db.BOMs.FirstOrDefault(t => t.MaterialNo == BomYM.MaterialNo);
            if (base_info == null)
            {
                Bom = new BOM();
            }
            else
            {
                Bom = base_info;
            }


            Bom.MaterialNo = BomYM.MaterialNo;
            Bom.ChildMaterialNo = BomYM.ChildMaterialNo;
          

            List<KeyValue<string>> pics= new List<KeyValue<string>>() { BomYM.Pictrue1 , BomYM.Pictrue2 , BomYM.Pictrue3 };
            foreach (var p in pics)
            {
                if(p!=null)
                {
                    //保存图片
                    string url = "/picture/" + p.Key;
                    string path = Directory.GetCurrentDirectory() + url;
                 
                    if(File.Exists(p.Value) )
                    {
                        try
                        {
                            File.Copy(p.Value, path);
                        }catch(Exception e)
                        {
                            if(File.Exists(path))
                            File.Delete(path);
                            File.Copy(p.Value, path);
                        }
                      
                      
                       
                    }

                    p.Value = url;
                }
            
            }

            Bom.PictureJson =JsonConvert.SerializeObject(pics);
            Bom.Remark = BomYM.Remark;
            Bom.Par = BomYM.Par;
            Bom.ChildJson = JsonConvert.SerializeObject(BomYM.BOMChildInfo);
            Bom.Company = 2;
            if (db.BOMs.Count(t => t.MaterialNo == BomYM.MaterialNo) != 0)
            {
                db.BOMs.Update(Bom);
            }
            else
            {
                db.BOMs.Add(Bom);
            }

            db.SaveChanges();
            MessageBox.Show("保存成功");

        }

        private void Delete(string obj)
        {
           
         
            MessageBox.Show("删除成功");
        }

        private void Init()
        {
            BomYM = new BOMYM();
         
            NSMaterials =new List<NSMaterialsViewModel>();
            db.NSMaterials.ToList().ForEach(t => {

                NSMaterials.Add(new NSMaterialsViewModel()
                {
                    NSMaterial = t,
                    AllName = t.Name + t.Type,
                });
            });
          
        }

        private void ChangePar(string obj)
        {
            DialogParameters keyValuePairs = new DialogParameters();
            keyValuePairs.Add("id", obj);
            dialogService.Show("BOMInfo", keyValuePairs, null);
        }

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
           
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            if (parameters != null && parameters.ContainsKey("id"))
            {

                var id = parameters.GetValue<string>("id");
                if(!string.IsNullOrEmpty(id) )
                {
                   Bom = db.BOMs.FirstOrDefault(t => t.ID == int.Parse(id));
                    BomYM.MaterialNo = Bom.MaterialNo;
                    BomYM.ChildMaterialNo = Bom.ChildMaterialNo;
                    if (!string.IsNullOrEmpty(Bom.PictureJson))
                    {
                        var pics= JsonConvert.DeserializeObject<List<KeyValue<string>>>(Bom.PictureJson) .ToList();
                        BomYM.Pictrue1 = pics[0];
                        BomYM.Pictrue2 = pics[1];
                        BomYM.Pictrue3 = pics[2];
                    }
                        
                    BomYM.Remark = Bom.Remark;
                    BomYM.Par = Bom.Par;
                    if(!string.IsNullOrEmpty(Bom.ChildJson))
                    BomYM.BOMChildInfo =JsonConvert.DeserializeObject<ObservableCollection<BOMChildInfo>> (Bom.ChildJson);

                }

               
              
            }
        
        }


        public  Microsoft.Win32.OpenFileDialog OpenDialogs()
        {
            var ofd = new Microsoft.Win32.OpenFileDialog()
            {
             
                FilterIndex = 1,
               
            };


            if (ofd.ShowDialog() != true)
                return null;
            return ofd;
        }





    }
}
